package cn.tedu._06article.base.config.exception;

import cn.tedu._06article.base.response.JsonResult;
import cn.tedu._06article.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalException {
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException exception)
    {
        String message= exception.getMessage();
        log.error("IllegalAccessException:"+message);
        return new JsonResult(StatusCode.OPERATION_FAILED,message);
    }
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public JsonResult doHandleRuntimeException(RuntimeException exception)
    {
        String message= exception.getMessage();
        log.error("doHandleRuntimeException:"+message);
        return new JsonResult(StatusCode.OPERATION_FAILED,message);
    }

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public JsonResult doHandle(Throwable exception)
    {
        String message= exception.getMessage();
        log.error("doHandle:"+message);
        return new JsonResult(StatusCode.OPERATION_FAILED,message);
    }
//    @ExceptionHandler(MethodArgumentNotValidException.class)
//    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
//        String data = ex.getFieldError().getDefaultMessage();
//        log.error("Throwable:" + data);
//        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
//    }
//
//    @ExceptionHandler(ConstraintViolationException.class)
//    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex)
//    {
//        String data=ex.getMessage().split(":")[1].trim();
//        return new JsonResult(StatusCode.VALIDATED_ERROR);
//    }
}
